<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="工单编号" prop="taskCode">
        <el-input
          v-model="queryParams.taskCode"
          placeholder="请输入工单编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工单状态" prop="taskStatus">
        <el-radio-group v-model="queryParams.taskStatus">
          <el-radio-button
            v-for="dict in task_status"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          @click="handleAdd"
          v-hasPermi="['manage:task:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          @click="handleTaskConfig"
          v-hasPermi="['manage:task:add']"
          >工单配置</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="taskList">
      <el-table-column
        label="序号"
        align="center"
        prop="taskId"
        type="index"
        width="55px"
      />
      <el-table-column label="工单编号" align="center" prop="taskCode" />
      <el-table-column label="售货机编码" align="center" prop="innerCode" />
      <el-table-column label="工单类型" align="center" prop="productTypeId">
        <template #default="scope">
          {{ getTaskTypeName(scope.row.productTypeId) }}
        </template>
      </el-table-column>
      <el-table-column label="工单方式" align="center" prop="createType">
        <template #default="scope">
          <dict-tag :options="task_create_type" :value="scope.row.createType" />
        </template>
      </el-table-column>
      <el-table-column label="工单状态" align="center" prop="taskStatus">
        <template #default="scope">
          <dict-tag :options="task_status" :value="scope.row.taskStatus" />
        </template>
      </el-table-column>
      <el-table-column label="运营人员" align="center" prop="userName" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.createTime, "{y}-{m}-{d}:{h}:{m}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="getTaskInfo(scope.row)"
            v-hasPermi="['manage:task:query']"
            >查看详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改运营工单对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="taskRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设备编码" prop="innerCode">
          <el-input
            v-model="form.innerCode"
            placeholder="请输入"
            @change="handelInnerCode"
          />
        </el-form-item>
        <el-form-item label="工单类型" prop="productTypeId">
          <el-input label="补货工单" disabled placeholder="补货工单" />
        </el-form-item>
        <!-- 补货详情按钮 -->
        <el-form-item
          label="工单详情"
          prop="taskDetail"
          v-if="form.innerCode != '' && form.innerCode != null"
        >
          <el-button
            type="primary"
            @click="handleAddDetail"
            v-hasPermi="['manage:task:add']"
            >补货详情</el-button
          >
        </el-form-item>
        <!-- 运营人员选择下拉框 -->
        <el-form-item label="运营人员" prop="userId">
          <el-select v-model="form.userId" placeholder="请选择" clearable>
            <el-option
              v-for="item in empList"
              :key="item.id"
              :label="item.userName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="desc">
          <el-input
            v-model="form.desc"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 补货详情对话框 -->
    <el-dialog
      title="补货详情"
      v-model="openDetail"
      width="900px"
      append-to-body
      @close="cancelDetail"
    >
      <el-table :data="channelList" height="250" style="width: 100%">
        <el-table-column prop="channelCode" label="货道编号"> </el-table-column>
        <el-table-column prop="sku.skuName" label="商品名称"> </el-table-column>
        <el-table-column prop="currentCapacity" label="当前数量">
        </el-table-column>
        <el-table-column prop="currentCapacity" label="还可添加数量">
          <template #default="scope">
            {{ scope.row.maxCapacity - scope.row.currentCapacity }}
          </template>
        </el-table-column>
        <el-table-column prop="expectCapacity" label="补满数量">
          <template #default="scope">
            <el-input-number
              min="0"
              :max="scope.row.maxCapacity - scope.row.currentCapacity"
              step="1"
              v-model="scope.row.expectCapacity"
              v-if="scope.row.currentCapacity < scope.row.maxCapacity"
            />
            <span v-else>货道已满</span>
          </template>
        </el-table-column>
      </el-table>
      <!-- 确认和取消按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitTaskDetail">确 定</el-button>
          <el-button @click="cancelTaskDetail">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 工单详情对话框 -->
    <el-dialog
      title="工单详情"
      v-model="openTaskDetail"
      width="500px"
      append-to-body
    >
      <el-descriptions :column="1" border="false" :data="taskInfo">
        <el-descriptions-item label="设备编码">{{
          taskInfo.innerCode
        }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{
          parseTime(taskInfo.createTime, "{y}-{m}-{d}:{h}:{m}:{s}")
        }}</el-descriptions-item>
        <el-descriptions-item
          v-if="taskInfo.updateTime != null && taskInfo.taskStatus == 4"
          label="完成时间"
        >
          {{ parseTime(taskInfo.updateTime, "{y}-{m}-{d}:{h}:{m}:{s}") }}
        </el-descriptions-item>
        <el-descriptions-item
          v-if="taskInfo.updateTime != null && taskInfo.taskStatus == 3"
          label="取消时间"
        >
          {{ parseTime(taskInfo.updateTime, "{y}-{m}-{d}:{h}:{m}:{s}") }}
        </el-descriptions-item>
        <el-descriptions-item label="运营人员">{{
          taskInfo.userName
        }}</el-descriptions-item>
        <el-descriptions-item label="工单类型">{{
          taskInfo.productTypeId == 2 ? "补货工单" : "工单类型错误"
        }}</el-descriptions-item>
        <el-descriptions-item label="补货数量">
          <el-button type="primary" @click="handleShowTaskDetail"
            >补货详情</el-button
          >
        </el-descriptions-item>
        <el-descriptions-item label="工单方式">{{
          taskInfo.createType == 1 ? "手动工单" : "自动工单"
        }}</el-descriptions-item>
        <el-descriptions-item label="工单状态">
          <dict-tag :options="task_status" :value="taskInfo.taskStatus" />
        </el-descriptions-item>
        <el-descriptions-item v-if="taskInfo.desc != null" label="备注">{{
          taskInfo.desc
        }}</el-descriptions-item>
        <el-descriptions-item v-if="taskInfo.taskStatus == 3" label="重新创建">
          <el-button type="primary" @click="handleReCreate">重新创建</el-button>
        </el-descriptions-item>
        <el-descriptions-item
          v-if="taskInfo.taskStatus == 1 || taskInfo.taskStatus == 2"
          label="取消工单"
        >
          <el-button type="primary" @click="handleCancelTask"
            >取消工单</el-button
          >
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
    <!-- 补货详情表 -->
    <el-dialog
      title="补货详情"
      v-model="openReplenishDetail"
      width="600px"
      border="false"
      append-to-body
    >
      <el-table
        :data="replenishDetailList"
        height="250"
        border
        style="width: 100%"
      >
        <el-table-column prop="channelCode" label="货道"> </el-table-column>
        <el-table-column prop="skuName" label="商品"> </el-table-column>
        <el-table-column prop="expectCapacity" label="补货数量">
        </el-table-column>
      </el-table>
    </el-dialog>
    <!-- 工单配置对话框 -->
    <el-dialog
      title="工单配置"
      v-model="openTaskConfig"
      width="500px"
      append-to-body
    >
      <el-form>
        <el-form-item label="补货警戒线">
          <el-input-number
            min="0"
            max="80"
            step="10"
            v-model="taskConfig"
            placeholder="请输入补货警戒线"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitTaskConfig">确 定</el-button>
          <el-button @click="cancelTaskConfig">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Task">
import {
  listTask,
  getTask,
  delTask,
  addTask,
  updateTask,
  getTaskConfig,
  updateTaskConfig,
} from "@/api/manage/task";
import { listTaskType } from "@/api/manage/taskType";
import { loadAllParams } from "@/api/page";
import {
  operationListByInnerCode,
  businessListByInnerCode,
} from "@/api/manage/emp";
import { getGoodsList } from "@/api/manage/channel";
import { reactive, ref } from "vue";
import { getReplenishDetails } from "@/api/manage/taskDetails";
import { get } from "@vueuse/core";

const { proxy } = getCurrentInstance();
const { task_status, task_create_type } = proxy.useDict(
  "task_status",
  "task_create_type"
);

const taskList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    taskCode: null,
    taskStatus: null,
    createType: null,
    userId: null,
    regionId: null,
    productTypeId: null,
    isRepair: false,
  },
  rules: {
    innerCode: [
      { required: true, message: "售货机编码不能为空", trigger: "blur" },
    ],
    userId: [{ required: true, message: "执行人id不能为空", trigger: "blur" }],
    productTypeId: [
      { required: true, message: "工单类型id不能为空", trigger: "blur" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

/**工单配置按钮 */
const openTaskConfig = ref(false);
const taskConfig = ref("");

//获取补货警戒线
function selectTaskConfig() {
  getTaskConfig(1).then((res) => {
    taskConfig.value = res.data;
  });
}
function handleTaskConfig() {
  openTaskConfig.value = true;
}
function submitTaskConfig() {
  updateTaskConfig({
    id: 1,
    alertValue: taskConfig.value,
  }).then(() => {
    openTaskConfig.value = false;
    selectTaskConfig();
    proxy.$modal.msgSuccess("修改成功");
  });
}
function cancelTaskConfig() {
  openTaskConfig.value = false;
}
/**取消工单按钮 */
function handleCancelTask() {
  //确认提示
  proxy.$modal
    .confirm("确认要取消工单吗？")
    .then(function () {
      return updateTask({
        taskId: taskInfo.value.taskId,
        taskStatus: 3,
      });
    })
    .then(() => {
      getTaskDetail(taskInfo.value.taskId);
      getList();
      proxy.$modal.msgSuccess("取消工单成功");
    })
    .catch(() => {});
}
/**获取工单详情 */
function getTaskDetail(taskId) {
  getTask(taskId).then((res) => {
    taskInfo.value = res.data;
  });
}
/**重新创建按钮 */
function handleReCreate() {
  reset();
  channelList.value = [];
  form.value = JSON.parse(JSON.stringify(taskInfo.value));
  businessListByInnerCode(form.value.innerCode).then((res) => {
    empList.value = res.rows;
  });
  open.value = true;
}
/**补货详情表 */
const replenishDetailList = ref([]);
const openReplenishDetail = ref(false);
function handleShowTaskDetail() {
  replenishDetailList.value = [];
  getReplenishDetails(taskInfo.value.taskId).then((res) => {
    replenishDetailList.value = res.data
  });
  openReplenishDetail.value = true;
}
/**补货详情按钮 */
const openDetail = ref(false);
const channelList = ref([]);
function handleAddDetail() {
  openDetail.value = true;
}
//补货详情确认按钮
function submitTaskDetail() {
  const taskDetailsList = [];
  for (let i = 0; i < channelList.value.length; i++) {
    if (
      channelList.value[i].expectCapacity != null &&
      channelList.value[i].expectCapacity > 0
    ) {
      taskDetailsList.push({
        channelCode: channelList.value[i].channelCode,
        skuId: channelList.value[i].sku.skuId,
        skuName: channelList.value[i].sku.skuName,
        skuImage: channelList.value[i].sku.skuImage,
        expectCapacity: channelList.value[i].expectCapacity,
      });
    }
  }
  form.value.taskDetailsList = taskDetailsList;
  openDetail.value = false;
}
/**查询货道信息 */
function getChannelList(innerCode) {
  getGoodsList(innerCode).then((response) => {
    channelList.value = response.data.filter(
      (channel) => channel.sku && channel.sku.skuId !== null
    ).map(channel => {
      return {
        ...channel,
        expectCapacity: channel.maxCapacity - channel.currentCapacity
      };
    });
  });
}
//补货详情取消按钮
function cancelTaskDetail() {
  openDetail.value = false;
  channelList.value = [];
  form.value.taskDetailsList = [];
}
/**查看详情按钮 */
const openTaskDetail = ref(false);
const taskInfo = ref({});
function getTaskInfo(row) {
  taskInfo.value = {};
  getTaskDetail(row.taskId);
  openTaskDetail.value = true;
}
/** 查询运营工单列表 */
function getList() {
  loading.value = true;
  listTask(queryParams.value).then((response) => {
    taskList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
/**查询工单类型列表 */
//根据id从工单类型列表中获取工单类型名称
function getTaskTypeName(typeId) {
  for (let i = 0; i < taskTypeList.value.length; i++) {
    if (taskTypeList.value[i].typeId == typeId) {
      return taskTypeList.value[i].typeName;
    }
  }
}
const taskTypeList = ref([]);
function getTaskTypeList() {
  listTaskType(loadAllParams).then((response) => {
    taskTypeList.value = response.rows;
  });
}
/**处理innerCode变化 */
const empList = ref([]);
async function handelInnerCode(value) {
  //重置数据
  form.value.userId = null;
  empList.value = [];
  channelList.value = [];
  if (value == null || value == "") {
    console.log("innerCode is null");
    return;
  }
  //查询可选员工列表
  businessListByInnerCode(value).then((response) => {
    empList.value = response.rows;
  });
  getChannelList(form.value.innerCode);
}
// 取消按钮
function cancel() {
  open.value = false;
  reset();
  channelList.value = [];
  empList.value = [];
}

// 表单重置
function reset() {
  form.value = {
    taskId: null,
    taskCode: null,
    taskStatus: null,
    createType: 1,
    innerCode: null,
    userId: null,
    userName: null,
    regionId: null,
    desc: null,
    productTypeId: 2,
    assignorId: null,
    addr: null,
    createTime: null,
    updateTime: null,
    taskDetailsList: [],
  };
  proxy.resetForm("taskRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.taskId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  empList.value = [];
  open.value = true;
  title.value = "添加运营工单";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _taskId = row.taskId || ids.value;
  getTask(_taskId).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改运营工单";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["taskRef"].validate((valid) => {
    if (channelList.value.length == 0 || channelList.value == null) {
      form.value.taskStatus = 1;
      updateTask(form.value).then((response) => {
        open.value = false;
        getTaskDetail(form.value.taskId);
        reset();
        getList();
      });
      return;
    }
    if (valid) {
      if (form.value.taskDetailsList.length == 0) {
        proxy.$modal.msgError("补货详情不能为空");
        return;
      }
      addTask(form.value).then((response) => {
        proxy.$modal.msgSuccess("新增成功");
        open.value = false;
        getList();
      });
      reset();
      channelList.value = [];
      empList.value = [];
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _taskIds = row.taskId || ids.value;
  proxy.$modal
    .confirm('是否确认删除运营工单编号为"' + _taskIds + '"的数据项？')
    .then(function () {
      return delTask(_taskIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "manage/task/export",
    {
      ...queryParams.value,
    },
    `task_${new Date().getTime()}.xlsx`
  );
}

selectTaskConfig();
getTaskTypeList();
getList();
</script>
